package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.MusicDao;
import entity.Music;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/deleteSelMusicServlet")
//删除选中的音乐
public class DeleteSelMusicServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");
        String[] sIds = req.getParameterValues("id[]");
        MusicDao musicDao = new MusicDao();
        int sum = 0;
        Map<String,Object> return_map = new HashMap<>();
        for (int i = 0 ; i < sIds.length; i ++){
            int id = Integer.parseInt(sIds[i]);
            Music music = musicDao.findMusicById(id);
            if (music == null) continue;
            //有当前需要删除的音乐
            int ret = musicDao.deleteMusicById(id);
            //事务回滚批量删除操作拓展
            if (ret == 1){
                //数据库删除成功，服务器上的数据也需要发生改变
                //删除服务器目录下的对应的文件
                File file = new File("D:\\项目\\music\\src" +
                        "\\main\\webapp\\"+music.getUrl()+".mp3");
                //删除格式不同，后缀要做相应改变.mp3,.docx等
                if (file.delete()){
                    sum += ret;
                }else {
                    return_map.put("msg",false);
                    System.out.println("删除失败！1");
                }
            }else{
                return_map.put("msg",false);
                System.out.println("删除失败！2");
            }
        }
        if(sum == sIds.length){
            return_map.put("msg",true);
            System.out.println("删除成功！");
        }
        else{
            return_map.put("msg",false);
            System.out.println("删除失败！3");
        }
        ObjectMapper mapper = new ObjectMapper();
        //利用Jackson将map转化为json对象，
        // writer 将转换后的json字符串保存到字符输出流中，最后给客户端
        mapper.writeValue(resp.getWriter(),return_map);
    }
}
